package handlers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hello/utils"
	"net/http"
)

// UploadFile 上传文件
func UploadFile(ctx *gin.Context) {
	// 从表单中获取文件
	file, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(http.StatusBadRequest, utils.JSONResult{
			Code:    http.StatusBadRequest,
			Message: "未找到上传的文件: " + err.Error(),
			Data:    nil,
		})
		return
	}

	// 保存文件到服务器
	dst := fmt.Sprintf("./uploads/%s", file.Filename)
	if err := ctx.SaveUploadedFile(file, dst); err != nil {
		ctx.JSON(http.StatusInternalServerError, utils.JSONResult{
			Code:    http.StatusInternalServerError,
			Message: http.StatusText(http.StatusInternalServerError),
			Data:    nil,
		})
		return
	}

	// 返回成功的JSON结果
	ctx.JSON(http.StatusOK, utils.JSONResult{
		Code:    http.StatusOK,
		Message: "文件上传成功",
		Data:    map[string]string{"filename": file.Filename},
	})
}
